<template>
  <span>
    <el-form-item :label="componentDef.name" :prop="componentDef.codeStart">
      <div v-if="formMode == 'edit' ">
        <el-date-picker
          v-model="dataRange"
          size="medium " 
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="onChange"
        >
        </el-date-picker>
      </div>
      <div v-else>
        <div v-text="showValue()"></div>
      </div>
    </el-form-item>
    <el-form-item style="display: none;" :prop="componentDef.codeEnd"></el-form-item>
  </span>
</template>

<script>
export default {
  name: 'SfDateRange',
  props: {
    componentDef: {
      type: Object,
      required: true
    },
    formMode: {
      type: String,
      required: true
    },
    formData: {
      type: Object,
      required: true
    }
  },
  data(){
    return {
      dataRange: null
    }
  },
  created() {
    this.initData()
  },
  watch: {
    formData: {
      handler(newVal) {
        console.log("SfDateRange watch", newVal); // oldVal好像不行
        if (this.formData[this.componentDef.codeStart] != this.getDataRangeStart() || this.formData[this.componentDef.codeEnd] != this.getDataRangeEnd()){
          console.log("SfDateRange change");  
          this.initData()
        }
      },
      deep: true,   // 关键配置
    }
  },
  methods: {
    getDataRangeStart(){
      if (this.dataRange == null || this.dataRange.length <= 1){
        return null
      } else {
        return this.dataRange[0]
      }
    },
    getDataRangeEnd(){
      if (this.dataRange == null || this.dataRange.length <= 1){
        return null
      } else {
        return this.dataRange[1]
      }
    },
    showValue(){
      return this.formData[this.componentDef.codeStart] + " ~ " + this.formData[this.componentDef.codeEnd]
    },
    initData(){
      if(this.formData[this.componentDef.codeStart] == null || this.formData[this.componentDef.codeEnd] == null ){
        this.dataRange = null
      } else {
        this.dataRange = [this.formData[this.componentDef.codeStart],this.formData[this.componentDef.codeEnd]]
      }
    },
    onChange(){
      if(this.getDataRangeStart() == null || this.getDataRangeEnd() == null){
        console.log("onChange null")
        this.formData[this.componentDef.codeStart] = null
        this.formData[this.componentDef.codeEnd] = null
      } else {
        console.log("onChange", this.getDataRangeStart(), this.getDataRangeEnd())
        this.formData[this.componentDef.codeStart] = this.getDataRangeStart()
        this.formData[this.componentDef.codeEnd] = this.getDataRangeEnd()
      }
    }
  }
}


</script>